package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.*;
import cn.wolfcode.wms.mapper.ProductStockMapper;
import cn.wolfcode.wms.mapper.StockIncomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockIncomeBillMapper;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IStockIncomeBillService;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StockIncomeBillServiceImpl implements IStockIncomeBillService {
    @Autowired
    private StockIncomeBillMapper stockIncomeBillMapper;
    @Autowired
    private StockIncomeBillItemMapper stockIncomeBillItemMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Override
    public void saveOrUpdate(StockIncomeBill entity) {
        if (entity.getItems().size() == 0) {
            throw new RuntimeException("至少要有1条商品明细");
        }
        if (!Optional.ofNullable(entity.getId()).isPresent()) {
            saveBill(entity);
        }else {
            updateBill(entity);
        }
    }
    //更新单据的业务操作
    private void updateBill(StockIncomeBill entity) {
        //判断当前单据是否是未审核状态的
        StockIncomeBill old = stockIncomeBillMapper.selectByPrimaryKey(entity.getId());
        if (old.getStatus() == StockIncomeBill.NO_AUDITED) {
            //删除旧的明细
            stockIncomeBillMapper.deleteItemsByBillId(entity.getId());
            //重新计算新的小计和总计
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (StockIncomeBillItem item : entity.getItems()) {
                //重新计算小计
                BigDecimal amount = item.getCostPrice()
                        .multiply(item.getNumber().setScale(2,RoundingMode.HALF_UP));
                item.setAmount(amount);
                //累加到总计上
                totalNumber = totalNumber.add(item.getNumber());
                totalAmount = totalAmount.add(amount);
                stockIncomeBillItemMapper.insert(item);
            }
            old.setTotalNumber(totalNumber);
            old.setTotalAmount(totalAmount);
            //新的信息同步过来
            old.setSn(entity.getSn());
            old.setVdate(entity.getVdate());
            old.setDepot(entity.getDepot());
            //更新单据
            stockIncomeBillMapper.updateByPrimaryKey(old);
        }
    }
    //新增单据的业务操作
    private void saveBill(StockIncomeBill entity) {
        //1.所有的关键信息必须手动设置一遍
        //单据状态 录入人 录入时间
        entity.setStatus(StockIncomeBill.NO_AUDITED);//设置默认未审核
        entity.setInputTime(new Date());//设置录入时间
        entity.setInputUser(UserContext.getCurrentUser());//本系统默认设置录入人为登陆人
        //2.重新后台计算明细的小计和单据的总计
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (StockIncomeBillItem item : entity.getItems()) {
            //重新计算小计
            BigDecimal amount = item.getCostPrice()
                    .multiply(item.getNumber().setScale(2,RoundingMode.HALF_UP));
            item.setAmount(amount);
            //累加到总计上
            totalNumber = totalNumber.add(item.getNumber());
            totalAmount = totalAmount.add(amount);
        }
        entity.setTotalAmount(totalAmount);
        entity.setTotalNumber(totalNumber);
        //保存到数据库
        stockIncomeBillMapper.insert(entity);
        //单据有多个,需遍历
        for (StockIncomeBillItem item : entity.getItems()) {
            //每个明细设置对应的单据ID
            item.setBillId(entity.getId());
            stockIncomeBillItemMapper.insert(item);
        }
    }

    @Override
    public void delete(Long id) {
        StockIncomeBill old = stockIncomeBillMapper.selectByPrimaryKey(id);
        //判断当前单据必须是未审核状态
        if (old.getStatus() == StockIncomeBill.NO_AUDITED) {
            //先删除明细再删除单据
            stockIncomeBillMapper.deleteItemsByBillId(id);
            stockIncomeBillMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public StockIncomeBill get(Long id) {
        return stockIncomeBillMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer rows = stockIncomeBillMapper.selectForCount(qo);
        if (rows == 0) {
            return PageResult.EMPTY_PAGE;
        }
        List<?> data = stockIncomeBillMapper.selectForList(qo);
        PageResult result = new PageResult(qo.getCurrentPage(),qo.getPageSize(),rows,data);
        return result;
    }

    @Override
    public void audit(Long id) {
        StockIncomeBill bill = stockIncomeBillMapper.selectByPrimaryKey(id);
        if (bill.getStatus() == StockIncomeBill.NO_AUDITED) {
            //未审核状态
            Depot depot = bill.getDepot();
            //拿到明细,存入数据库
            for (StockIncomeBillItem item : bill.getItems()) {
                //拿到当前明细中进入的商品
                Product p = item.getProduct();
                //查询当前仓库中是否有该商品
                ProductStock ps = productStockMapper.selectByDepotIdAndProductId(depot.getId(), p.getId());
                //判断是否还有库存
                if (Optional.ofNullable(ps).isPresent()) {
                    //移动加权平均,重新计算库存价格
                    //先算小计
                    BigDecimal amount = ps.getAmount().add(item.getAmount());
                    //再算数量
                    BigDecimal number = ps.getStoreNumber().add(item.getNumber());
                    //加权平均,算库存价格
                    BigDecimal price = amount.divide(number, RoundingMode.HALF_UP);
                    //新的数据设置到库存对象中
                    ps.setAmount(amount);
                    ps.setStoreNumber(number);
                    ps.setPrice(price);
                    //更新到数据库
                    productStockMapper.updateByPrimaryKey(ps);
                }else {
                    //没此商品的库存,第一次进货,可直接存入
                    ps = new ProductStock();
                    ps.setProduct(p);
                    ps.setPrice(item.getCostPrice());
                    ps.setStoreNumber(item.getNumber());
                    ps.setAmount(item.getAmount());
                    ps.setDepot(depot);
                    productStockMapper.insert(ps);
                }
                //审核操作本身相关的数据
                bill.setStatus(StockIncomeBill.AUDITED);
                bill.setAuditor(UserContext.getCurrentUser());
                bill.setAuditTime(new Date());
                stockIncomeBillMapper.audit(bill);
            }
        }
    }
}
